package com.hrbxlh.action;

import java.awt.Color;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import javax.swing.text.rtf.RTFEditorKit;

import com.hrbxlh.util.PubMethods;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.QuestionActionImpl;
import com.hrbxlh.actionImpl.SourceActionImpl;
import com.hrbxlh.util.SourceExcel;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.html.table.Table;
import com.lowagie.text.rtf.style.RtfFont;


@Controller
public class ExcelTest {
	@Autowired
	@Qualifier("sourceActionImpl")
	private SourceActionImpl sourceActionImpl;
	
	@Autowired
	@Qualifier("questionActionImpl")
	private QuestionActionImpl questionActionImpl;
	//日志信息
	Logger logger = Logger.getLogger(ExcelTest.class.getName());

/**
 *
    * 成绩导出Excel 
    * @param model 
    * @param projectId
    * @param request 
    * @return 
 * @throws Exception 
    */  
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/sourceExcel", method = RequestMethod.GET)
    public ModelAndView sourceExcel(String jsonStr,ModelMap model,HttpServletRequest request,HttpSession session) throws Exception{
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		//获取页面参数值
		Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
		preParamMap.put("pageNow", 0);
		preParamMap.put("pageSize", 10);
		Map<String, Object> resultAllMap = sourceActionImpl.getAllSourceList(preParamMap,session,request);
		List<Map<String,Object>> memberList = (List<Map<String, Object>>) resultAllMap.get("excelMemberList");
		if(memberList!=null&&memberList.size()!=0){
			String[] keys = new String[]{ "stuorteaId","userName","className","courseName","preforSource","examSource","sumSource"};
	        String[] titles = new String[]{ "学号","姓名","班级","课程", "平时成绩","考试成绩","总成绩"};
	        String fileName = "学生成绩信息";
	        SourceExcel defaultExcelView = new SourceExcel();
	        model.put("memberList", memberList);
	        model.put("keys", keys);
	        model.put("titles", titles);
	        model.put("fileName", fileName);
	        logger.info("成绩导出Excel ,参数为："+jsonStr+"求过的结果model"+model);
		    return new ModelAndView(defaultExcelView, model);
		}else{
			//存放结果值
			Map<String,Object> resultMap = new HashMap<String,Object>();
			resultMap.put("errMsg", "当前暂无数据");
			//存放页面
			String pageName = "noResourceShow";
			reJsonStr = mapper.writeValueAsString(resultMap);
			resultMap.put("result", reJsonStr);
			logger.info("成绩导出Excel结果为："+reJsonStr);
		    return new ModelAndView(pageName, resultMap);
		}
        
    }  
	
	/** 
	    * 生成试题pdf 
	    * @param model 
	    * @param projectId 
	    * @param request 
	    * @return 
	 * @throws Exception 
	    */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/questionWord", method = RequestMethod.GET)
	public String questionWord(ModelMap model,String jsonStr, HttpServletRequest request,HttpSession session,HttpServletResponse response) throws Exception{
		String pageName = "";
		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> paraMap = new HashMap<String,Object>();
		//获取参数值
		Map<String,Object> paramMap = mapper.readValue(jsonStr, paraMap.getClass());
		String type = String.valueOf(paramMap.get("type"));
		//取分数值
		logger.info(paramMap.get("optionSorce")+" "+paramMap.get("judgeSource")+" "+paramMap.get("blanksSource")+" "+paramMap.get("answerSource"));
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//返回字符串
		String reJsonStr = "";
		OutputStream out = response.getOutputStream();
		ItextManager tm = ItextManager.getInstance();
		ITextWord iword = ITextWord.getInstance();
		logger.info("生成试题前台传的参数"+paramMap);
		Map<String,Object> resultMap = questionActionImpl.getAllQuestionListExcel(paramMap,request);
		resultMap.put("fileName",paramMap.get("fileName"));
		Map<String,Object> courseMap = new HashMap<String,Object>();
		courseMap = (Map<String, Object>) resultMap.get("courseMap");
		logger.info("查询课程map"+courseMap);
		String fileName =courseMap.get("courseName")+new SimpleDateFormat("yyyyMMdd").format(new Date())+"试题.pdf";
		String fileName1 =courseMap.get("courseName")+new SimpleDateFormat("yyyyMMdd").format(new Date()) +"试题.doc";
		fileName = new String(fileName.getBytes("UTF-8"),"ISO-8859-1");
		fileName1 = new String(fileName1.getBytes("UTF-8"),"ISO-8859-1");
		response.setContentType("application/octet-stream; charset=UTF-8");
		if("word".equals(type)){
			response.setHeader("content-disposition","attachment;filename=" + fileName1);
		}else if("pdf".equals(type)){
			response.setHeader("content-disposition", "attachment;filename=" +fileName);
		}

		if(resultMap!=null){
			logger.info("生成试题的resultMap不为空"+resultMap);
//		    	 tm.createRtfContext(resultMap,out,type,paramMap);
			iword.createRtfContext(resultMap,out,type,paramMap);
			out.flush();
			out.close();
			return null;
		}else{
			logger.info("生成试题的resultMap为空"+resultMap);
			Map<String,Object> finalMap = new HashMap<String,Object>();
			finalMap.put("errMsg", "当前课程在题库中没有相应的试题，生成试题失败");
			logger.error("当前课程在题库中没有相应的试题，生成试题失败");
			reJsonStr = mapper.writeValueAsString(finalMap);
			returnMap.put("result", reJsonStr);
			logger.error("生成试题返回的结果为"+reJsonStr);
			return "redirect:/errAction";
		}

	}
		
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/errAction", method = RequestMethod.GET)
	 public ModelAndView errAction() throws Exception{
			 Map<String,Object> finalMap = new HashMap<String,Object>();
			 String pageName="";
			//返回字符串
			String reJsonStr = "";
			//转换json格式工具
			ObjectMapper mapper = new ObjectMapper();
			//存放返回值
			Map<String, Object> returnMap = new HashMap<String, Object>();
			try{
			 
				 finalMap.put("errMsg", "当前课程在题库中没有相应的试题，生成试题失败");
				 pageName = "error";
			 
		 }catch(Exception e){
			 finalMap.put("errMsg", "当前课程在题库中没有相应的试题，生成试题失败");
			 pageName="error";
		 }finally{
			reJsonStr = mapper.writeValueAsString(finalMap);
			returnMap.put("result", reJsonStr);
			logger.error("走错误页action返回结果为："+reJsonStr);
		 }
		return new ModelAndView(pageName, returnMap);
	 }
	
}
